/**
 * 
 */
package org.bf.sms.util;

import java.io.IOException;
import java.io.StringWriter;

import org.apache.log4j.Logger;
import org.bf.sms.domain.user.Account;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;


/**
 * JSON 转换工具类
 * 
 * @author LiuChang
 * @version 1.0 2010-12-08
 * @since 1.0
 */
public class JSONTranslator
{

	private static final Logger LOGGER = Logger.getLogger(JSONTranslator.class);

	/**
	 * 
	 */
	private static final ObjectMapper MAPPER = new ObjectMapper();

	/**
	 * 
	 */
	private JSONTranslator()
	{

	}

	/**
	 * @return
	 */
	public static ObjectMapper getInstance()
	{
		return MAPPER;
	}

	/**
	 * 将JSON串转换为bean
	 * 
	 * @param <T>
	 * @param json
	 * @param clazz
	 * @return
	 */
	public static <T> T toBean(String json, Class<T> clazz)
	{
		try {
			return MAPPER.readValue(json, clazz);
		}
		catch (JsonParseException e) {
			JSONTranslator.LOGGER.error("toBean", e);
		}
		catch (JsonMappingException e) {
			JSONTranslator.LOGGER.error("toBean", e);
		}
		catch (IOException e) {
			JSONTranslator.LOGGER.error("toBean", e);
		}

		return null;
	}

	/**
	 * 将bean转换为JSON串
	 * 
	 * @param object
	 * @return
	 */
	public static String toJSON(Object object)
	{
		StringWriter sw = new StringWriter();
		JsonGenerator gen;
		try {
			gen = new JsonFactory().createJsonGenerator(sw);
			MAPPER.writeValue(gen, object);
			gen.close();
			return sw.toString();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		return null;

	}

	/**
	 * test code
	 * 
	 * @param args
	 */
	public static void main(String[] args)
	{
		Account account = new Account();
		account.setUsername("aaa");
		account.setPassword("bbb");
		System.out.println(toBean(
				"{\"id\":0,\"username\":\"aaa\",\"password\":\"bbb\"}",
				Account.class));
	}
}